/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.config.idgenerator;

import org.openislands.oi.util.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;

@Component
public class NodeIdGenerator {
    private static final Logger log = LoggerFactory.getLogger(NodeIdGenerator.class);
    private static int id = 0;

    public long getUID() {
        try {
            if (id == 0) {
                Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = allNetInterfaces.nextElement();
                    if (!netInterface.isLoopback() && !netInterface.isVirtual() &&
                            !netInterface.isPointToPoint() && netInterface.isUp()) {
                        StringBuilder sb = new StringBuilder();
                        byte[] mac = netInterface.getHardwareAddress();
                        if (mac != null) {
                            for (byte b : mac) {
                                sb.append(String.format("%02X", b));
                            }
                        }
                        int macHashId = sb.toString().hashCode();
                        // 16 bits unsigned
                        int processId = Integer.parseInt(ProcessUtils.getProcessId());
                        id = macHashId << 16 | processId;
                        log.info("worker node id:" + id);
                        return id;
                    }
                }
                return 0;
            } else {
                return id;
            }
        } catch (SocketException e) {
            return 0;
        }
    }

    public String getNodeId() {
        return UUID.randomUUID().toString().replace("-", "") + Long.toHexString(getUID());
    }
}
